package com.daniel.dianping.interceptor;


import com.daniel.dianping.dto.UserDTO;
import com.daniel.dianping.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    // 验证是否可以登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取用户
        UserDTO userDTO = UserHolder.getUser();
        // 2.判断用户是否存在
        if (userDTO == null) {
            // 不存在，拦截返回401
            response.setStatus(401);
            return false;
        }
        // 3.放行
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
